import {Coverage, TestParser} from '../../test-parser'
import {readFile,checkCoverageFileExist} from '../../utils'
import * as cheerio from 'cheerio'
import * as step from '@flow-step/step-toolkit'

export class JavaJUnitParser implements TestParser {
    async coverageFile(path: string): Promise<string> {
        if (!path.endsWith('.html')) {
            throw new Error(`Input variable 'reportPath' should reference a report with html extension`)
        }

        await checkCoverageFileExist(path)
        return path
    }

    htmlFile(path: string): string {
        return path
    }

  async parse(path: string): Promise<Coverage> {
      step.info(`Parsing Java-JUnit Html report: ${path}`)
      const htmlContent = await readFile(path)
      step.debug(`htmlContent: ${htmlContent}`)
      return this.count(htmlContent)
  }

  async count(htmlContent: string): Promise<Coverage>{
      const $ = cheerio.load(htmlContent)
      let res = {
          total : 0,
          passed : 0,
          failed : 0,
          skipped : 0,
          passedRate : 0
      } as Coverage

      $('tr.b').first().find('td').each((index: number, element: any) => {
          switch (index)  {
              case 0:
                  res.total = parseInt($(element).text(),10)
                  break
              case 1:
                  res.failed += parseInt($(element).text(),10)
                  break
              case 2:
                  res.failed += parseInt($(element).text(),10)
                  break
              case 3:
                  res.skipped = parseInt($(element).text(),10)
                  break
          }
      })

      res.passed = res.total - res.failed - res.skipped
      if (res.total != 0){
          res.passedRate = Math.round(res.passed / res.total * 10000) / 100
      }
      return res
  }
}
